//
//  PictureSelectorViewController.swift
//  01-照片选择器
//
//  Created by 唐万超 on 15/8/10.
//  Copyright © 2015年 唐万超. All rights reserved.
//

import UIKit
/// 可重用标识符
private let reuseIdentifier = "PictureSelectorViewIdentifier"

class PictureSelectorViewController: UICollectionViewController, PictureSelectorCellDelegate {

    // 懒加载
    lazy var photos = [UIImage]()
    // 当前选中照片的索引
    var currentIndex = 0
    
    init() {
        
        super.init(collectionViewLayout: UICollectionViewFlowLayout())
        
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
    
        prepareCollectionView()
       
    }
    
    private func prepareCollectionView() {
        
        collectionView?.registerClass(PictureSelectorCell.self, forCellWithReuseIdentifier: reuseIdentifier)
        
        let layout = collectionView?.collectionViewLayout as? UICollectionViewFlowLayout
        
        layout?.itemSize = CGSize(width: 80, height: 80)
        
        layout?.sectionInset = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
        
        collectionView?.backgroundColor = UIColor.whiteColor()
        
    }
    
    // MARK: - 数据源方法

    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of items
        return photos.count + 1
    }

    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! PictureSelectorCell
    
        cell.picture = (indexPath.item < photos.count) ? photos[indexPath.item] : nil
        cell.backgroundColor = UIColor.blueColor()
        
        cell.delegate = self
        
        return cell
    }
    
    // 实现代理方法
    /// 选择照片
    private func photoSelectorCellSelectPhoto(cell: PictureSelectorCell) {
        // 判断是否支持访问相册
        if !UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.PhotoLibrary) {
        
            print("无法访问照片库")
            return
        }
        
        let picker = UIImagePickerController()
        picker.delegate = self
        
        // 记录选中照片的index
        let index = collectionView!.indexPathForCell(cell)
        
        currentIndex = index!.item
        
        presentViewController(picker, animated: true, completion: nil)
    }
    /// 删除照片
    private func photoSelectorCellRemovePhoto(cell: PictureSelectorCell) {
        
        // 取到点中的照片
        let index = collectionView!.indexPathForCell(cell)
        
        photos.removeAtIndex(index!.item)
        
        collectionView?.reloadData()
        
    }
   
}
// MARK: - 选择照片的代理方法   

extension PictureSelectorViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        
        let scaleImage = image.scaleImage(300)
        
        // 对选中的照片进行判断
        if currentIndex == photos.count {
            // 添加照片
            photos.append(scaleImage)
        } else {
            
            // 说明选中新图片
            photos[currentIndex] = scaleImage
        }
        
       
        // 刷新数据
        collectionView?.reloadData()
        
        dismissViewControllerAnimated(true, completion: nil)
        
    }
}

// MARK: - 手写代理
private protocol PictureSelectorCellDelegate: NSObjectProtocol {

    // 代理方法
    func photoSelectorCellSelectPhoto(cell: PictureSelectorCell)
    func photoSelectorCellRemovePhoto(cell: PictureSelectorCell)
}

private class PictureSelectorCell: UICollectionViewCell {
    
    var picture: UIImage? {
        didSet{
            if picture == nil {
                photoButton.setImage("compose_pic_add")
            }else {
                 photoButton.setImage(picture, forState: UIControlState.Normal)
            }
            // 设置删除按钮在加号上隐藏
            removeButton.hidden = (picture == nil)
        }
        
    }
    
    // 设置代理属性
    weak var delegate: PictureSelectorCellDelegate?
    
    // 图片按钮点击
    @objc func photoClick() {
        delegate?.photoSelectorCellSelectPhoto(self)
    }
    
    // 删除按钮点击
   @objc func removeClick() {
         delegate?.photoSelectorCellRemovePhoto(self)
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // 设置界面
    private func setupUI() {
    
        contentView.addSubview(photoButton)
        contentView.addSubview(removeButton)
        
        // 设置约束
        photoButton.translatesAutoresizingMaskIntoConstraints = false
        removeButton.translatesAutoresizingMaskIntoConstraints  = false
        
        let dict = ["pb" : photoButton, "rb" : removeButton]
        
        contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[pb]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: dict))
        contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[pb]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: dict))
        contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:[rb]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: dict))
        contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[rb]", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: dict))
        
        photoButton.addTarget(self, action: "photoClick", forControlEvents: UIControlEvents.TouchUpInside)
        removeButton.addTarget(self, action: "removeClick", forControlEvents: UIControlEvents.TouchUpInside)
        
        // 设置图片的填充模式
        photoButton.imageView?.contentMode = UIViewContentMode.ScaleAspectFill
        
    }
    
    // MARK: - 懒加载控件
    private lazy var photoButton: UIButton = UIButton(imageName: "compose_pic_add")
    
    private lazy var removeButton: UIButton = UIButton(imageName: "compose_photo_close")
    
}
